<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              部件名称：<el-input placeholder="请输入内容" v-model="selectForm.componentName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              部件编码：
              <el-input placeholder="请输入内容" v-model="selectForm.componentCode" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              部件类型：
              <el-select v-model="selectForm.componentType" clearable placeholder="请选择">
                <el-option v-for="(item,index) in componentTypeOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>&nbsp;
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows"
            v-on:checkSingleRow="checkSingleRow"
            v-on:changeSingleRow="changeSingleRow"
            v-on:deleSingleRow="deleSingleRow">
          </app-table>
          <el-dialog title="添加部件" :visible.sync="dialogFormVisible" class="custom-dialog_style_twoLine" :before-close="cancel">
            <el-form :model="formData" :rules="rules" ref="formData" :disabled="showOnly" label-width="120px" size="mini">
              <el-form-item label="部件名称：" prop="componentName" label-width="30%">
                <el-input v-model="formData.componentName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="部件编码：" prop="componentCode" label-width="30%">
                <el-input v-model="formData.componentCode" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="部件类型：" prop="componentType" label-width="30%">
                <el-select v-model="formData.componentType" clearable filterable placeholder="请选择">
                  <el-option v-for="(item,index) in componentTypeOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="" label-width="30%">
              </el-form-item>
              <el-form-item label="选择经纬度：" prop="longitude" class="custom-longla-container">
                <el-input v-model="formData.longitude" :disabled="true" placeholder="经度"></el-input>
                <el-input v-model="formData.latitude" :disabled="true" placeholder="纬度"></el-input>
                <el-button type="text" @click="openSimpleMap" style="color: red;">[ 选择 ]</el-button>
              </el-form-item>
              <el-form-item label="" label-width="30%">
              </el-form-item>
              <el-form-item label="图片：" class="custom-img-container" style="width:100%">
                <app-upload ref="appUpload" v-model="formData.pictureArr"></app-upload>
              </el-form-item>
              <el-form-item label="街道/社区/网格：" prop="gridIdArr" label-width="30%">
                <div class="block">
                  <el-cascader placeholder="请选择"
                    :options="treeData"
                    filterable
                    clearable
                    :props="gridIdProps"
                    v-model="formData.gridIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="部门：" prop="deptIdArr" label-width="30%">
                <div class="block">
                  <el-cascader placeholder="请选择"
                    :options="deptOption"
                    filterable
                    clearable
                    :props="gridIdProps"
                    v-model="formData.deptIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="简介：" label-width="30%" class="custom-textarea-container">
                <el-input type="textarea" v-model="formData.remark"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog class="dialog-body-mini" :visible.sync="showMap" title="选择经纬度" width="70%" top="8vh" :before-close="mapCancel">
            <edit-map v-if="showMap" :mode="mapMode" @appMapCallback="appMapCallback" :target="mapTarget"></edit-map>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppUpload from '@/components/AppMultiUpload'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import EditMap from '@/components/EditMap'
import {getAllRegion} from '@/utils/region'
import {isCommonDo} from '@/utils/CommonUtil'
import {createMapLocation, updateMapLocation} from '@/http/AppApi'
import {getUserGridTree, getUserDeptTree} from '@/utils/SessionDataUtil'
import {findComponent, createComponent, updateComponent, delComponent} from '@/http/UnitApi'
import {getDictDataOption} from '@/utils/getDictDataOption'
export default {
  data () {
    return {
      dialogFormVisible: false,
      mapHackReset: false,
      showMap: false,
      mapMode: 'simple',
      mapTarget: {},
      treeData: [],
      pageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'componentName', label: '部件名称' },
        { prop: 'componentCode', label: '部件编码' },
        { prop: 'componentType', label: '部件类型', formatter: this.componentTypeFormmatter }
      ],
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      tableDada: [],
      deptOption: [],
      selectForm: {},
      formData: {},
      rules: {
        componentName: [
          { required: true, message: '请输入部件名称：', trigger: 'blur' }
        ],
        componentCode: [
          { required: true, message: '请输入部件编码', trigger: 'blur' }
        ],
        componentType: [
          { required: true, message: '请选择部件类型', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '请选择经纬度', trigger: 'blur' }
        ],
        deptIdArr: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        gridIdArr: [
          { required: true, message: '请选择网格', trigger: 'blur' }
        ]
      },
      componentTypeOption: []
    }
  },
  components: {
    EditMap,
    AppTree,
    BtnGroup,
    AppTable,
    AppUpload
  },
  mounted () {
    this.getTreeData()
    this.getDeptTreeData()
    this.getTableData()
    this.componentTypeOption = getDictDataOption('部件类型')
  },
  methods: {
    componentTypeFormmatter (row, column) {
      let componentTypeOption = this.componentTypeOption
      let resComponentType = ''
      for (let i = 0; i < componentTypeOption.length; i++) {
        if (componentTypeOption[i].code === row.componentType) {
          resComponentType = componentTypeOption[i].name
          break
        }
      }
      return resComponentType
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    getDeptTreeData () {
      let data = getUserDeptTree()
      if (data && data instanceof Array) {
        this.deptOption = data
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.isObjEmpty(this.formData)) return
          this.dialogFormVisible = false
          if (this.formData.gridIdArr && this.formData.gridIdArr !== 0) {
            let index = this.formData.gridIdArr.length - 1
            let data = {}
            data.id = this.formData.gridIdArr[index]
            data.items = this.treeData
            data.isGetAllId = true
            this.formData.allGridId = getAllRegion(data)
          } else {
            this.formData.allGridId = ''
          }
          let deptIdIndex = this.formData.deptIdArr.length - 1
          this.formData.departmentId = this.formData.deptIdArr[deptIdIndex]
          if (this.formData.pictureArr) {
            this.formData.picture = this.formData.pictureArr.length === 0 ? '' : this.formData.pictureArr.join(',')
          }
          if (this.formData.id) {
            updateComponent(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          } else {
            createComponent(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delComponent(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs.appUpload.clearFileList()
    },
    getTableData (param) {
      findComponent(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          isCommonDo(this.pageData, this)
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    handleCurrentChange (val) {
      let param = {
        offset: (val - 1) * 10
      }
      this.getTableData(param)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        if (callbackData.btnType === 'post') {
          if (this.formData.gridIdArr) {
            let arr = this.formData.gridIdArr
            this.formData = {}
            this.$set(this.formData, 'gridIdArr', arr)
          } else {
            this.formData = {}
          }
        } else {
          let data = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(data)
          this.formData.pictureArr = this.toArray(this.formData.picture)
          let regionData = {}
          regionData.id = this.formData.gridId
          regionData.items = this.treeData
          let gridIdArr = getAllRegion(regionData)
          this.$set(this.formData, 'gridIdArr', gridIdArr)
          let deptData = {}
          deptData.id = this.formData.departmentId
          deptData.items = this.deptOption
          let deptIdArr = getAllRegion(deptData)
          this.$set(this.formData, 'deptIdArr', deptIdArr)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    toArray (string) {
      let arr = []
      if (string) {
        let stringArr = string.split(',')
        for (let i = 0; i < stringArr.length; i++) {
          let obj = {}
          obj.name = 'IMG_' + i
          obj.url = stringArr[i]
          arr.push(obj)
        }
        return string.split(',')
      } else {
        return []
      }
    },
    checkSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    changeSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    deleSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      }
    },
    appTreeClick (data) {
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.treeData
      let gridIdArr = getAllRegion(gridData)
      this.$set(this.formData, 'gridIdArr', gridIdArr)
      this.getTableData({ likeAllGridId: data.id })
    },
    searchHandleClick () {
      if (this.isObjEmpty(this.selectForm)) return
      this.getTableData(this.selectForm)
    },
    openSimpleMap () {
      this.mapMode = 'simple'
      this.showMap = true
      this.mapHackReset = true
      // 注释
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        if (appMapInfo.target.targetId) {
          let mapLocation = {}
          if (appMapInfo.poly && appMapInfo.poly instanceof Array && appMapInfo.poly.length > 0) {
            let length = appMapInfo.poly.length
            this.saveMapLocationInfoByArray(0, length, appMapInfo)
          } else {
            mapLocation = this.appMapInfo2MapLocation(appMapInfo)
            this.saveMapLocationInfo(mapLocation)
          }
        } else {
          this.showOnly = false
          this.showMap = false
          this.$set(this.formData, 'latitude', appMapInfo.lnglat.lat)
          this.$set(this.formData, 'longitude', appMapInfo.lnglat.lng)
        }
      }
      return ''
    },
    appMapInfo2MapLocation (appMapInfo) {
      let mapLocation = {}
      mapLocation.targetId = appMapInfo.target.targetId
      mapLocation.targetType = appMapInfo.target.targetType

      if (!appMapInfo.poly) {
        mapLocation.mapArea = appMapInfo.polyPathArr
        mapLocation.mapColor = appMapInfo.polyColor
        // 地图信息id存在则不允许修改targetId和targetType
        if (appMapInfo.id) {
          mapLocation.id = appMapInfo.id
          delete mapLocation.targetId
          delete mapLocation.targetType
        }
      }
      if (appMapInfo.clearStatus) {
        mapLocation.clearStatus = appMapInfo.clearStatus
      }
      if (appMapInfo.markPosition) {
        mapLocation.longitude = appMapInfo.markPosition.lng
        mapLocation.latitude = appMapInfo.markPosition.lat
        if (appMapInfo.id) {
          mapLocation.id = appMapInfo.id
        }
      }
      return mapLocation
    },
    saveMapLocationInfoByArray (i, length, appMapInfo) {
      if (i >= length) {
        return
      }
      let mapLocation = {}
      mapLocation = this.appMapInfo2MapLocation(appMapInfo)
      mapLocation.mapArea = appMapInfo.poly[i].polyPathArr
      mapLocation.mapColor = appMapInfo.poly[i].polyColor
      mapLocation.id = appMapInfo.poly[i].id
      if (mapLocation.id) {
        delete mapLocation.targetId
        delete mapLocation.targetType
      }
      i++
      let data = mapLocation
      console.log('maplocation id = ' + mapLocation.id)
      if (mapLocation.id) {
        updateMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('修改成功')
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          } else {
            console.log(resp.message)
          }
        })
      } else {
        createMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('保存成功')
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          } else {
            console.log(resp.message)
          }
        })
      }
    },
    saveMapLocationInfo (mapLocation) {
      if (mapLocation.id) {
        updateMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('修改成功')
          } else {
            console.log(resp.message)
          }
        })
      } else {
        createMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('保存成功')
          }
        })
      }
      this.mapCancel()
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    },
    isObjEmpty (obj) {
      for (var key in obj) {
        return false
      }
      return true
    }
  }
}
</script>
<style scoped>
.custom-dialog_style_twoLine .el-form >>> .custom-img-container .el-form-item__content {
  position: relative;
}
.custom-dialog_style_twoLine .el-form >>> .custom-img-container .el-form-item__label {
  width: 25%!important
}
.custom-dialog_style_twoLine .el-form .custom-img-container {
  margin-bottom: 20px
}
</style>
